<template>
  <div class="section-container">
    <div class="section-title">
      数据源列表
    </div>
    <div class="section-actions">
      <div class="actions-left">
        <el-button v-permission="['setting:dataSource:list:add']" type="primary" @click="handleAdd()">新增数据源</el-button>
        <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleSearch" />
      </div>
    </div>
    <div class="table-box">
      <RuifoxTable :loading="tableLoading" :default-index="true" :default-checkbox="false" v-model:tableData="tableData" v-model:fieldList="fieldList">
        <template #groupId="{ element }">
          <div>{{ groupMapping[element.groupId] }}</div>
        </template>
        <template #options="{ element }">
          <div class="table-td-option">
            <el-button v-permission="['setting:dataSource:list:edit']" type="primary" link @click="handleEdit(element)">编辑</el-button>
            <el-button v-permission="['setting:dataSource:list:delete']" type="primary" link @click="handleDelete(element.id)">删除</el-button>
          </div>
        </template>
      </RuifoxTable>
      <div class="header-page">
        <PaginationView
          :total="queryData.total"
          :pageSize="queryData.pageSize"
          :currentPage="queryData.currentPage"
          :allChoose="isAllChooseBtn"
          :pageChoose="isPageChooseBtn"
          :canChoose="false"
          :checkedNum="checkedNum"
          @changeSize="handleSizeChange"
          @currentChange="handleCurrentChange"
          @changePageChoose="handlePageChoose"
          @changeAllChoose="handleAllChoose"
          @invertChoose="handleInvertChoose"
          @refreshList="getTableData"
          @cancelChoose="handleResetPagination"
        />
      </div>
    </div>
    <el-dialog v-model="dataSourceDialog" :title="dataSourceTitle" width="700px">
      <el-form :model="dataSourceForm" ref="dataSourceRef" :rules="dataSourceRules" label-width="auto" style="max-width: 600px">
        <el-form-item label="所属团队" prop="groupId">
          <el-tree-select v-model="dataSourceForm.groupId" :data="groupTreeData" :props="groupTreeProps" :expand-on-click-node="false" check-strictly default-expand-all node-key="id" />
        </el-form-item>
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="dataSourceForm.name" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="dataSourceForm.username" />
        </el-form-item>
        <el-form-item label="登录密码">
          <el-input v-model="dataSourceForm.password" />
        </el-form-item>
        <el-form-item label="所属服务" prop="path">
          <el-input v-model="dataSourceForm.path" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dataSourceDialog = false">取消</el-button>
          <el-button type="primary" @click="dataSourceSubmit(dataSourceRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getDataSourcePage, insertDataSource, updateDataSource, deleteDataSource } from '@/api/dataSource'
import { selectGroupList } from '@/api/team'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tableList as mixTable, createMapping } from '@ruifox-cms/utils'
import { createTreeData2 } from '@/utils/tools'

const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleResetPagination
} = mixTable({
  getListApi: getDataSourcePage
})
tableData.value = []

const fieldList = ref([
  {
    title: '名称',
    name: 'name'
  },
  {
    title: '用户名',
    name: 'username'
  },
  {
    title: '密码',
    name: 'password'
  },
  {
    title: '所属团队',
    name: 'groupId',
  },
  {
    title: 'url',
    name: 'url',
    minWidth: 400,
    showTextTip: true
  },
  {
    title: '操作',
    width: 120,
    fixed: 'right',
    name: 'options'
  }
])

// 获取全部团队
const groupTreeData = ref([])
const groupMapping = ref({})
const groupTreeProps = {
  label: 'name',
  value: 'id'
}
const getAllGroup = async () => {
  const res = await selectGroupList()
  if (res.code == 20000) {
    groupTreeData.value = createTreeData2(res.data)
    searchCmpArray.value[2].options = groupTreeData.value
    groupMapping.value = createMapping(res.data, { keyProp: 'id', valueProp: 'name' })
  }
}
getAllGroup()

// 搜索条件
const defaultQueryData = reactive({
  path: '', // 后端服务模块名
  name: '', // 数据源名
  groupId: '' // 团队id
})
Object.assign(queryData, defaultQueryData)
const searchCmpArray = ref([
  { label: '数据源名称', key: 'name' },
  { label: '所属模块', key: 'path' },
  { label: '所属团队', key: 'groupId', form_type: 'treeSelect', options: groupTreeData.value, props: {label: 'name', value: 'id'}}
])

// 新增
const dataSourceRules = reactive({
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  name: [{ required: true, message: '请输入组件名称', trigger: 'blur' }],
  proUrl: [{ required: true, message: '请输入线上地址', trigger: 'blur' }]
})
const defaultDataSourceForm = reactive({
  "groupId": 0,
  "name": "",
  "password": "",
  "path": "",
  "url": "",
  "username": ""
})
const dataSourceForm = ref({})
const dataSourceTitle = ref('新增数据源')
const dataSourceDialog = ref(false)
const handleAdd = () => {
  dataSourceTitle.value = '新增数据源'
  dataSourceForm.value = structuredClone(defaultDataSourceForm)
  dataSourceDialog.value = true
  if (dataSourceRef.value) dataSourceRef.value.clearValidate()
}

// 编辑
const handleEdit = data => {
  dataSourceForm.value = structuredClone(data)
  dataSourceTitle.value = '编辑数据源'
  dataSourceDialog.value = true
}

// 删除
const handleDelete = async (id) => {
  ElMessageBox.confirm('是否删除所选接口？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      let res = await deleteDataSource({id})
      if (res.code == 20000) {
        handleResetPagination()
        ElMessage({
          showClose: true,
          message: `删除成功`,
          type: 'success'
        })
        getTableData()
      }
    })
}

// 提交
const dataSourceRef = ref()
const dataSourceSubmit = async formEl => {
  if (!formEl) return
  await formEl.validate(async valid => {
    if (valid) {
      let res = null
      if (dataSourceForm.value.checked != null) delete dataSourceForm.value.checked
      if (dataSourceForm.value.id == null) {
        res = await insertDataSource(dataSourceForm.value)
      } else {
        res = await updateDataSource(dataSourceForm.value)
      }
      if (res.code == 20000) {
        ElMessage({
          showClose: true,
          message: `${dataSourceTitle.value}成功`,
          type: 'success'
        })
        dataSourceDialog.value = false
        getTableData()
      }
    }
  })
}

onMounted(() => {
  handleSearch()
})
</script>
<style scoped lang="scss">

</style>
